import requests
import pandas as pd
import io
import pymysql
import json

import urllib.request
import re
import datetime
from apscheduler.schedulers.blocking import BlockingScheduler
#
# 一共用到 getIndustry， getSHSZTickRTSnapshot， getIndustryPriceRTSnapshot， getIdxConsTickRTSnapshot， getHEYEMktIndi
# 五个 api,
# 个股方面信息本来可以不用 getIdxConsTickRTSnapshot 这个， 通过 getSHSZTickRTSnapshot 这个接口也可获取， 只是需要统计一下， 如何统计， 参考上一个 cell 的代码
# 文档说明可以在 apidoc.datayes.com 上根据上面的名字搜索， 有些 api 是不对外的， 如果找不到， 请联系一下客服， 可以保存成 html 后给用户
def get_data(api_path, params):
    """
    将 XXXYYYZZZ 替换为用户的 token, token 在数据商城 -> 我的数据 -> 我的凭证 里可以看到
    https://mall.datayes.com/mydata?lang=zh
    """
    url = "{}{}".format("https://api.wmcloud.com/data/v1/", api_path)
    p_str = "&".join(["{}={}".format(k, params[k]) for k in params])
    data = requests.get("?".join([url, p_str]), data=params, headers={"Authorization": "Bearer {}".format("072eca62dcb2d4dd8b0aa761f275d0cbcba1bdf1ea070605a51ee1ce374934b2")})
    return pd.read_csv(io.StringIO(data.text))


# 27 个申万一级行业
industryUrl = "api/master/getIndustry.csv"
params = {"industryVersionCD": "010303", "isNew": "1", "industryLevel": "1", "field": "industrySymbol"}

industryIDs = ",".join([str(i) for i in get_data(industryUrl, params)["industrySymbol"].values])


def market_snapshot():
    strtime = datetime.datetime.now().strftime('%H-%M')
    h = int(strtime.split('-')[0])
    m = int(strtime.split('-')[1])
    if h == 9 and m < 25:
        return
    if h == 11 and m > 35:
        return
    if h == 12 and m < 55:
        return
    if h == 15 and m > 5:
        return
    if h == 16:
        return

    print("大盘方面：")
    index_snapshot = get_data("api/market/getSHSZTickRTSnapshot.csv",
                              {"assetClass": "idx", "ticker": "000001,399106,399102,399101", "exchangeCD": "XSHE,XSHG"})
    index_snapshot["updown"] = index_snapshot.apply(lambda row: "上涨" if row["change"] >= 0 else "下跌", axis=1)
    shstr=szstr=cystr=zxstr=''
    for i, row in index_snapshot.iterrows():
        if row['ticker'] == 1:
            shstr= "{} 当前点位 {:.2f}, {} {:.2f} 点, 涨跌幅 {:.4f}, 成交金额 {:10.2f}".format(row["shortNM"],
                                                            row["lastPrice"],
                                                            row["updown"],
                                                            abs(row["change"]),
                                                            row["changePct"],
                                                            row["value"])
        if row['ticker'] == 399106:
            szstr= "{} 当前点位 {:.2f}, {} {:.2f} 点, 涨跌幅 {:.4f}, 成交金额 {:10.2f}".format(row["shortNM"],
                                                            row["lastPrice"],
                                                            row["updown"],
                                                            abs(row["change"]),
                                                            row["changePct"],
                                                            row["value"])
        if row['ticker'] == 399102:
            cystr="{} 当前点位 {:.2f}, {} {:.2f} 点, 涨跌幅 {:.4f}, 成交金额 {:10.2f}".format(row["shortNM"],
                                                            row["lastPrice"],
                                                            row["updown"],
                                                            abs(row["change"]),
                                                            row["changePct"],
                                                            row["value"])
        if row['ticker'] == 399101:
            zxstr= "{} 当前点位 {:.2f}, {} {:.2f} 点, 涨跌幅 {:.4f}, 成交金额 {:10.2f}".format(row["shortNM"],
                                                            row["lastPrice"],
                                                            row["updown"],
                                                            abs(row["change"]),
                                                            row["changePct"],
                                                            row["value"])

        print("{} 当前点位 {}, {} {} 点, 涨跌幅 {}, 成交金额 {}".format(row["shortNM"],
                                                            row["lastPrice"],
                                                            row["updown"],
                                                            abs(row["change"]),
                                                            row["changePct"],
                                                            row["value"]))


    #
    industry_snapshot = get_data("api/market/getIndustryPriceRTSnapshot.csv", {"industryID": industryIDs})
    # industry_snapshot = DataAPI.IndustryPriceRTSnapshotGet(industryID=industryIDs)
    up_industries = industry_snapshot[industry_snapshot["chgPct"] > 0].sort_values(["chgPct"],
                                                                                   ascending=[False]).head(5)
    down_industries = industry_snapshot[industry_snapshot["chgPct"] < 0].sort_values(["chgPct"], ascending=[True]).head(
        5)
    Industrygains5="当前无行业上涨"
    industrydecline5="当前无行业下跌"

    # up_industries = industry_snapshot[industry_snapshot["chgPct"] > 0].sort_values(["chgPct"],
    #                                                                                ascending=[False]).head(5)
    # down_industries = industry_snapshot[industry_snapshot["chgPct"] < 0].sort_values(["chgPct"], ascending=[True]).head(
    #     5)
    # if up_industries.empty:
    #     print("当前无行业上涨")
    # else:
    #     up_industries["t"] = up_industries.apply(lambda row: row["industryName"] + "(" + str(row["chgPct"]) + ")",
    #                                              axis=1)
    #     print("当前涨幅前 5 的行业： {}".format(", ".join(up_industries["t"].values)))
    #
    # if down_industries.empty:
    #     print("当前无行业上涨")
    # else:
    #     down_industries["t"] = down_industries.apply(lambda row: row["industryName"] + "(" + str(row["chgPct"]) + ")",
    #                                                  axis=1)
    #     print("当前跌幅前 5 的行业： {}".format(", ".join(down_industries["t"].values)))


    if up_industries.empty:
        print("当前无行业上涨")

    else:
        #cpstr ="{:.4f}".formart(row["chgPct"])
        up_industries["t"] = up_industries.apply(lambda row: row["industryName"],
                                             axis=1)

        print("当前涨幅前 5 的行业： {}".format(", ".join(up_industries["t"].values)))
        Industrygains5="当前涨幅前 5 的行业： {}".format(", ".join(up_industries["t"].values))


    if down_industries.empty:
        print("当前无行业下跌")
    else:
        #cpstr = "{:.4f}".formart(row["chgPct"])
        down_industries["t"] = down_industries.apply(lambda row: row["industryName"] ,
                                                     axis=1)
        print("当前跌幅前 5 的行业： {}".format(", ".join(down_industries["t"].values)))

        industrydecline5="当前跌幅前 5 的行业： {}".format(", ".join(down_industries["t"].values))

    print("\n个股方面：")
    ticker_snapshot = get_data("api/market/getIdxConsTickRTSnapshot.csv",
                               {"ticker": "DY0001,399102", "field": "ticker,upNum,downNum,equalNum"})
    a_up = ticker_snapshot[ticker_snapshot["ticker"] == "DY0001"]["upNum"].values[0]
    a_equal = ticker_snapshot[ticker_snapshot["ticker"] == "DY0001"]["equalNum"].values[0]
    a_down = ticker_snapshot[ticker_snapshot["ticker"] == "DY0001"]["downNum"].values[0]
    s_up = ticker_snapshot[ticker_snapshot["ticker"] == "399102"]["upNum"].values[0]
    s_equal = ticker_snapshot[ticker_snapshot["ticker"] == "399102"]["equalNum"].values[0]
    s_down = ticker_snapshot[ticker_snapshot["ticker"] == "399102"]["downNum"].values[0]
    print("当前 A 股上涨 {} 家, 其中创业板 {} 家; 平盘 {} 家, 其中创业板 {} 家; 下跌 {} 家, 其中创业板 {} 家".format(a_up, s_up, a_equal, s_equal,
                                                                                       a_down, s_down))
    downup = ("当前 A 股上涨 {} 家, 其中创业板 {} 家; 平盘 {} 家, 其中创业板 {} 家; 下跌 {} 家, 其中创业板 {} 家".format(a_up, s_up, a_equal, s_equal,
                                                                                       a_down, s_down))



    print("\n涨跌停方面：")
    heye_indi = get_data("api/market/getHEYEMktIndi.csv", {})
    print("当前涨停 {} 家， 跌停 {} 家".format(heye_indi["upLimitNum"][0], heye_indi["downLimitNum"][0]))

    downuplimt ="当前涨停 {} 家， 跌停 {} 家".format(heye_indi["upLimitNum"][0], heye_indi["downLimitNum"][0])

    db = pymysql.connect(host="39.105.19.0", user="root",password="My123$ql", db="stock-demo", port=3306,charset='utf8')
    cur = db.cursor()
    sqlinsert ="insert into stockdatafromtl(sh,sz,cy,zx,Industrygains5,industrydecline5,downup,downuplimit)values(%s,%s,%s,%s,%s,%s,%s,%s)"

    try:
        cur.execute(sqlinsert,(shstr,szstr,cystr,zxstr,Industrygains5,industrydecline5,downup,downuplimt))
        db.commit()
    except:
        db.rollback()


    cur.close()
    db.close()



def main():
    #9: 30 - 11:30，下午时段13: 00 - 15:00




    sched = BlockingScheduler()
    sched.add_job(market_snapshot, 'cron', day_of_week='mon-fri', hour ='9-12,13-18', minute='*/2')
    sched.start()

if __name__ == '__main__':
    main()